package com.basic.technology.study.introduction.thread.callablefuture;

import java.util.concurrent.*;

public class CallableAndFuture {
    public static void main(String[] args) {
        // Callable + Future   -----------------
        CallableAndFuture callableAndFuture = new CallableAndFuture();
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = callableAndFuture.new Task();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();
        // Callable + Future   -----------------

        // Callable + FutureTask   ------方式1-----------
//        CallableAndFuture callableAndFuture = new CallableAndFuture();
//        ExecutorService executor = Executors.newCachedThreadPool();
//        Task task = callableAndFuture.new Task();
//        FutureTask<Integer> result = new FutureTask<>(task);
//        executor.submit(result);
//        executor.shutdown();
        // Callable + FutureTask   -----------------

        // Callable + FutureTask   ------方式2-----------
        // 第二种方式，注意这种方式和第一种方式效果是类似的，只不过一个使用的是ExecutorService，一个使用的是Thread
//        CallableAndFuture callableAndFuture = new CallableAndFuture();
//        Task task = callableAndFuture.new Task();
//        FutureTask<Integer> result = new FutureTask<Integer>(task);
//        Thread thread = new Thread(result);
//        thread.start();
        // Callable + FutureTask   -----------------

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果" + result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }

    class Task implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < 100; i++) {
                sum += i;
            }
            return sum;
        }
    }
}
